<!-- 销售管理->面积计算表出入库情况 -->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <btns-wrapper :hideRevocation="true" @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer" @clickEdit="clickEdit" @deleteOrder="deleteOrder" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" @priceShow="priceShow" :sourceCode="sourceCode">

                </btns-wrapper>

            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div>
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="table-box">

                            <ux-grid style="width: 100%" class="ux-table" cellStyle="height:36px;" border :sum-text="合计" show-summary :summaryMethod="summaryMethod" show-body-overflow ref="plxTable" keep-source height="500" :edit-config="{trigger: 'click', mode: 'cell'}">
                                <ux-table-column type="checkbox" width="60" align="center"></ux-table-column>
                                <ux-table-column :field="item.key" :label="item.title" v-for="(item,index) in columns" :key="index" :title="item.title" :width="item.width" :min-width="item.key == 'number'?30:80" height="32">
                                    <template v-if="item.key != 'number'" v-slot:edit="scope">
                                        <a-input v-model="scope.row[item.key]" @input="updateFooterEvent(scope.row[item.key])"></a-input>
                                    </template>
                                </ux-table-column>
                            </ux-grid>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>
                </section>
                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <importAndExport ref="importAreaRef" @syncFun="syncFun" @backArea="backArea"></importAndExport>
        <a-modal :visible="priceModal" title="报价" @cancel="closePrice" :width="1000">
            <ux-grid style="width: 100%" class="ux-table" cellStyle="height:36px;" border show-body-overflow ref="priceTable" keep-source height="500" :edit-config="{trigger: 'click', mode: 'cell'}">
                <ux-table-column :field="item.key" :label="item.title" v-for="(item,index) in columnsPrice" :key="index" :title="item.title" :width="item.width" :min-width="item.key == 'number'?30:80" height="32" :editRender="item.key == 'price' ?true:false">
                    <template v-if="item.key == 'price'" v-slot:edit="scope">
                        <a-input onkeyup="value=value.toString().match(/^\d+(?:\.\d{0,2})?/)" v-model.trim="scope.row[item.key]"></a-input>
                    </template>
                </ux-table-column>
            </ux-grid>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="okPirce">确认</a-button>
                    <a-button @click="closePrice" class="margin-left-10">关闭</a-button>
                </div>
            </template>
        </a-modal>
    </div>
</template>
<script>


import { save, examine, remove, getCode, exportAreaData, setPrice, getInOutRecord } from '@/api/sale/areaCalculation'


import pro from '@/mixins/procurement/pro';
import importAndExport from "@/components/ImportAndExport/index"
import Template from '../crm/activity/template.vue';

export default {
    mixins: [pro],
    components: {
        importAndExport
    },
    data () {
        return {
            //基础 查询条件（列表 + 翻页）
            basePostData: {
                someBusinessType: null,
            },
            financeType: true,
            sourceCode: 'AreaCalculation',
            reportCodeDetail: 'AreaCalculation_Detail_Report',          //明细code
            reportCodeStatistical: 'AreaCalculation_Statistic_Report',   //统计code
            reportCodeList: 'AreaCalculation_List_Report',              //列表code
            checkType: 'is_for_sale',//销售

            tableData: [],
            totalOptions: [
                { label: '数量', unit: '元' },
                { label: '长', unit: '个' }
            ],
            priceModal: false,
            dataSourcePrice: [],

            notEdit: ['inNum', 'outNum', 'number', 'price', 'amount'],//不能编辑的字段
            isAreaX: true,//是否是新西亚项目
            areaInOut: true,
            dataSourceNumber: 11,    //明细table初始多少条
            totalYes: ['quantity', 'unitArea', 'totalArea'],//需要合计的字段
        };
    },
    created () {
        //this.getIdByData();//获取最新一条数据
    },
    mounted () {
        // 延迟加载
        setTimeout(() => {
            console.log(this.columns)
            // this.columns = Array.from({ length: 200 }, (_, idx) => ({
            //     prop: 'name',
            //     id: idx,
            //     label: '名字' + idx,
            //     width: 200,
            //     sortable: idx === 1,
            //     resizable: true
            // }))

            // this.tableData = Array.from({ length: 500 }, (_, idx) => ({
            //     id: idx + 1,
            //     date: '2016-05-03',
            //     name: '张三' + idx,
            //     sex: 1,
            //     age: 18 + idx,
            //     time: '9:10',
            //     address: ['zhinan', 'shejiyuanze', 'kekong'],
            //     single: idx < 2
            // }))
            // console.log('this.tableData:', this.tableData);
            // console.log('this.dataSource:', this.dataSource);

            // col.forEach((item, index) => {
            //     if (item.key == 'number') {
            //         col.splice(index, 1);
            //     }
            // });



            // 这样设置大量数据的表格
            this.dataSource = this.dataSource.filter((res, index) => { return index != this.dataSource.length - 1 })

            this.dataSource.forEach((item, index) => {
                item.number = index + 1;
            });
            this.$refs.plxTable.reloadData(this.dataSource)
            // 获取表格实例，里面可以得到列，表格数据等等
            console.log(this.$refs.plxTable.tableExample())
        }, 1000);
    },
    watch: {
        dataSourcePrice: {
            handler (newVal, oldVal) {
                newVal.forEach(item => {
                    if (item.price != null && item.price != 0) {
                        //计算金额
                        item.amount = (item.price * item.quantity).toFixed(2);
                    }
                })
            },
            deep: true,
        }
    },
    methods: {
        closePrice () {
            //关闭报价
            this.priceModal = false;
        },
        priceShow () {
            //报价弹窗
            this.priceModal = true;

            this.columnsPrice = this.columns;
            this.dataSourcePrice = _.cloneDeep(this.dataSource);

            this.$nextTick(() => {
                this.$refs.priceTable.reloadData(this.dataSourcePrice)
            })
        },
        getInOutRecord () {
            //获取出入库数量
            let data = this.orderData;
            let requestData = {
                sourceVoucherId: data.id,
                sourceVoucherType: this.sourceCode,
            }
            getInOutRecord(requestData).then(res => {
                if (res.code === 200) {
                    if (res.data.length > 0) {
                        this.inOutData = res.data;
                        let map = new Map();
                        this.inOutData.forEach(e => {
                            map.set(e.sourceDetailId, e)
                        });
                        console.log(map);
                        this.dataSource.forEach(item => {
                            if (map.get(item.id)) {
                                item.inNum = map.get(item.id).inNum;
                                item.outNum = map.get(item.id).outNum;
                            }

                        });
                        console.log(this.dataSource)
                    }
                }
            })
        },
        okPirce () {
            //确认报价
            console.log(this.dataSourcePrice);
            let data = _.cloneDeep(this.thisPageData);
            data.reviewerDate = null;
            data.createDate = null;
            data.detailList = [];
            data.orderDetailList = this.dataSourcePrice.filter(res => res.price != null && res.price != 0);
            setPrice(data).then(res => {
                if (res.code === 200) {
                    this.$message.success('报价成功');
                    this.priceModal = false;
                } else {
                    // this.$message.warning(res.message);
                }
            }).catch(err => {
                this.$message.warning(err)
            })
        },
        summaryMethod ({ columns, data }) {
            //合计
            const means = [];
            columns.forEach((column, columnIndex) => {
                if (columnIndex === 0) {
                    means.push('合计')
                } else {
                    const values = data.map(item => Number(item[column.property]));
                    // 合计
                    if (!values.every(value => isNaN(value))) {
                        if (column.property == 'number') {
                            means[columnIndex] = '';
                        } else {
                            if (this.totalYes.includes(column.property)) {
                                means[columnIndex] = values.reduce((prev, curr) => {
                                    const value = Number(curr);
                                    if (!isNaN(value)) {
                                        return prev + curr;
                                    } else {
                                        return prev;
                                    }
                                }, 0);
                                means[columnIndex] = means[columnIndex].toFixed(2);
                            }
                        }
                    } else {
                        means[columnIndex] = '';
                    }
                }
            })
            // 返回一个二维数组的表尾合计
            return [means]
        },
        // 更新合计
        updateFooterEvent (num) {
            // 这里执行了updateFooter，然后就自动会去执行你的summaryMethod合计方法啦
            this.$refs.plxTable.updateFooter()
        },
        // 添加插入行
        async insertEvent (row) {
            console.log(this.dataSource.length)
            let record = {
                number: this.dataSource.length + 1
            }
            this.dataSource.push({})
            // 加入行, 表示加入行的row对象，row为空则插入第一行，为-1插入最后一行
            let { row: newRow } = await this.$refs.plxTable.insertRow(record, row)
            // 激活单元格编辑
            await this.$refs.plxTable.setActiveRow(newRow)
        },
        priceData () {
            //报价
        },
        importData () {
            //导入数据
            this.$refs.importAreaRef.importAreaFile();
        },
        exportData () {
            //导出数据
            exportAreaData({ orderId: this.orderId }).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "面积计算表.xls");
                document.body.appendChild(link);
                link.click();
            });
        },
        //新增预测单
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);

            setTimeout(() => {
                this.$refs.plxTable.reloadData(this.dataSource)
            }, 800)
        },
        //保存
        submit (requestData) {
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            const { sourceCode } = this;
            getCode({ dataSource: sourceCode }).then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        backArea (data) {
            //导入返回的数据
            data.orderDetailList.forEach((item, index) => {
                item.number = index + 1;
            })
            this.dataSource = data.orderDetailList;

            this.orderHeaderData.forEach(item => {
                if (data[item.code] != null) {
                    if (item.code == 'projectId') {//项目id转name
                        item.value = data.projectName;
                    } if (item.code == 'calculationUserId') { //员工id转name
                        item.value = data.calculationUserName;
                    } else {
                        item.value = data[item.code]
                    }
                }
            });
            this.$refs.plxTable.reloadData(this.dataSource)
            this.reload();
        },
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .ux-table {
        .ant-input {
            border: 1px solid #000 !important;
            padding: 2px !important;
        }
        .elx-table .elx-cell {
            padding: 0 5px;
        }
    }
</style>
